<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="auto">
            <el-form-item label="来源下游" prop="channelId">
                <el-select v-model="queryParams.channelId" filterable placeholder="来源下游" clearable size="small">
                    <el-option
                        v-for="item in classesList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="请求类型" prop="businessTypeStr">
                <el-select v-model="queryParams.businessTypeStr" placeholder="请选择请求类型" clearable size="small">
                    <el-option
                        v-for="item in businessTypeStrList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="操作时间">
                <el-date-picker
                    v-model="dateRange"
                    :picker-options="pickerOptions"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="['00:00:00', '23:59:59']"
                    align="right"
                    size="small"
                    clearable
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getFacet"></right-toolbar>
        </el-row>

        <div>
            <el-button @click="handleDimension('createTimeMap.y')" :type="queryParams.dimension == 'createTimeMap.y'?'primary':''">年度统计</el-button>
            <el-button @click="handleDimension('createTimeMap.ym')" :type="queryParams.dimension == 'createTimeMap.ym'?'primary':''">月度统计</el-button>
            <el-button @click="handleDimension('createTimeMap.ymd')" :type="queryParams.dimension == 'createTimeMap.ymd'?'primary':''">每日统计</el-button>
            <el-button @click="handleDimension('createTimeMap.ymdh')" :type="queryParams.dimension == 'createTimeMap.ymdh'?'primary':''">每时统计</el-button>
            <el-button @click="handleDimension('createTimeMap.ymdhm')" :type="queryParams.dimension == 'createTimeMap.ymdhm'?'primary':''">每分统计</el-button>
        </div>

        <div v-loading="loading">
            <label>时间统计</label>
            <line-chart :chartData="lineChartData" />
        </div>
        <div v-loading="loading">
           <el-row :gutter="24">
               <el-col :span="12">
                   <label>渠道统计</label>
                   <pie-chart :chartData="pieChartData" />
               </el-col>
               <el-col :span="12">
                   <label>类型统计</label>
                   <bar-chart :chartData="barChartData" />
               </el-col>
           </el-row>
        </div>

    </div>

</template>

<script>
    import {
        facet,
        channelFacet,
        businessTypeFacet,
        channelList
    } from "@/api/business/statistics"


    import {parseTime, getPreviousDate} from "@/utils/ruoyi";
    import LineChart from '@/components/Echarts/LineChart'
    import PieChart from '@/components/Echarts/PieChart'
    import BarChart from '@/components/Echarts/BarChart'

    export default {
        name: "index",
        components: {
            LineChart,
            PieChart,
            BarChart
        },
        data() {
            return {
                // 遮罩层
                loading: false,
                // 显示搜索条件
                showSearch: true,
                lineChartData: {
                    xData:[],
                    yData: []
                },
                pieChartData: {
                    legendData: [],
                    seriesData: [],
                },
                barChartData: {
                    xData:[],
                    yData: []
                },
                // 日期范围
                dateRange: [],
                queryParams: {
                    channelId: "",
                    businessTypeStr: "",
                    dimension: "createTimeMap.y"
                },
                businessTypeStrList: [{
                    label: "上报",
                    value: "ESCALATION"
                }, {
                    label: "回调",
                    value: "CALLBACK"
                }],
                classesList: [],
                pickerOptions: {
                    shortcuts: [{
                        text: '本日',
                        onClick(picker) {
                            const endStr = parseTime(new Date(), "{y}-{m}-{d} 23:59:59")
                            const end = new Date(endStr);

                            const startStr = parseTime(new Date(), "{y}-{m}-{d} 00:00:00")
                            const start = new Date(startStr);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '本月',
                        onClick(picker) {
                            const currYear = parseTime(new Date(), "{y}")
                            const currMonth = parseTime(new Date(), "{m}")
                            const endStr = parseTime(new Date(currYear, currMonth, 0), "{y}-{m}-{d} 23:59:59")
                            const end = new Date(endStr);

                            const startStr = parseTime(new Date(), "{y}-{m}-01 00:00:00")
                            const start = new Date(startStr);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '本年',
                        onClick(picker) {
                            const endStr = parseTime(new Date(), "{y}-12-31 23:59:59")
                            const end = new Date(endStr);

                            const startStr = parseTime(new Date(), "{y}-01-01 00:00:00")
                            const start = new Date(startStr);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },

            }
        },
        created() {
            this.getChannelList();
            this.getFacet()
        },
        mounted() {
        },
        methods: {
            getChannelList() {
                channelList().then(response => {
                    this.classesList = response.data.list.map(item => {
                        return {
                            label: item.title,
                            value: item.id
                        }
                    })

                });
            },
            handleDimension(type) {
                this.queryParams.dimension = type
                this.getFacet();
            },
            getFacet() {
                this.loading = true;
                let timeMap = {}
                this.addDateRange(timeMap, this.dateRange)
                Object.keys(timeMap.params).map(key => {
                    this.queryParams[key] = timeMap.params[key]
                })
                Promise.all([this.timeFacet(),this.channelFacet(),this.businessTypeFacet()]).then(() => {
                    this.loading = false;
                }).catch(err => {
                    console.error(err)
                });

            },
            async timeFacet() {
                await facet(this.queryParams).then(response => {
                    try{
                        let facetMap = response.data.facet[this.queryParams.dimension];
                        let xData = [];
                        let yData = [];

                        Object.keys(facetMap).map(key => {
                            xData.push(key);
                        });
                        xData.sort();
                        xData.map(key => {
                            yData.push(facetMap[key])
                        })
                        this.lineChartData = {
                            xData: xData,
                            yData: yData
                        }
                    }catch (e) {
                        console.log(e)
                    }
                });
            },
            async channelFacet() {
                await channelFacet(this.queryParams).then(response => {
                    try{
                        let facetMap = response.data.facet["params.channelId"];
                        let seriesData = [];
                        let legendData = [];

                        Object.keys(facetMap).map(key => {
                            legendData.push(key);
                            seriesData.push({
                                value: facetMap[key],
                                name: key
                            })
                        });
                        this.pieChartData = {
                            legendData: legendData,
                            seriesData: seriesData,
                        }
                    }catch (e) {
                        console.log(e)
                    }
                });
            },
            async businessTypeFacet() {
                await businessTypeFacet(this.queryParams).then(response => {
                    try{
                        let facetMap = response.data.agg["channelId"];
                        let xData = [];


                        let l1 = [];
                        let l2 = [];
                        Object.keys(facetMap).map(key => {
                            xData.push(key);
                            l1.push(facetMap[key]["businessTypeStr"]["ESCALATION"] || 0)
                            l2.push(facetMap[key]["businessTypeStr"]["CALLBACK"] || 0)
                        });
                        this.barChartData = {
                            xData: xData,
                            yData: [
                                {
                                    name: "上报",
                                    value: l1
                                },
                                {
                                    name: "回调",
                                    value: l2
                                }
                            ],
                        }
                    }catch (e) {
                        console.log(e)
                    }
                });
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getFacet();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
        }

    }
</script>

<style scoped>

</style>
